#include <event2/event.h>
#include <signal.h>

void sigint_cb(int sock, short which, void *arg)
{
    printf("signal int\r\n");
    event_base *base = (event_base*)arg;
    /*执行完当前处理的事件函数就退出*/
    //event_base_loopbreak(base);

    //运行所有的活动事件再退出
    //事件循环没有运行时也要等运行一次再退出
    timeval t = {3,0};
    event_base_loopexit(base, &t);
}

void sigkill_cb(int sock, short which, void *arg)
{
    printf("kill event\r\n");
    event *ev = (event*) arg;

    if(!evsignal_pending(ev, NULL)){
        event_del(ev);
        event_add(ev,NULL);
    }
}

int main() {
    bool isexit = false;
    event_base *base = event_base_new();
    /* add signal */
    event *csig = evsignal_new(base,SIGINT, sigint_cb, base);
    if(!csig){
        perror("create signal event failed\r\n");
        return -1;
    }
    
    if(evsignal_add(csig, 0) != 0){
        perror("add signal event failed\r\n");
        return -1;
    }

    /* add kill signal */
    event *ksig = event_new(base, SIGTERM, EV_SIGNAL, sigkill_cb, event_self_cbarg());
    
    if(evsignal_add(ksig, 0) != 0){
        perror("add signal event failed\r\n");
        return -1;
    }
    
    event_base_dispatch(base);

    /*EVLOOP_ONCE 等待一个事件运行，直到没有活动事件就退出*/
    /*EVLOOP_NONBLOCK 等待一个事件运行，直到没有活动事件就退出
    while(!isexit){
        event_base_loop(base, EVLOOP_NONBLOCK);
    }*/

    /* EVLOOP_NO_EXIT_ON_EMPTY 没有注册事件也不返回，用于事件后期多线程添加*/
    //event_base_loop(base, EVLOOP_NO_EXIT_ON_EMPTY);
    

    event_free(csig);
    event_base_free(base);

    return 1;

}